    #-*- encoding: utf-8 -*-
# Create your views here.
from django.template import Context, loader
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from profiles.models import Article, Comment, Vocabulary, Choice, Poll
from profiles.models import Category, File, University, Institution
from profiles.models import About, Contact, Saved_institution
from profiles.models import Saved_article, Saved_university
from profiles.models import Read_article, Read_university, Read_institution, Banner, About_toefl
from registration.models import RegistrationProfile
from django.contrib.auth.models import User
from django.forms import ModelForm
from django.core.context_processors import csrf
from django.core.urlresolvers import reverse
from django.http import Http404
from django.core.files.base import ContentFile
from django.views.decorators.csrf import csrf_exempt
from filetransfers.api import serve_file

import re
from django.db.models import Q

import random
from django.contrib.auth.decorators import login_required

class Comment_article_form(ModelForm):
    class Meta:
        model = Comment
        exclude = ["article"]
        
        
class Comment_file_form(ModelForm):
    class Meta:
        model = Comment
        exclude = ["file"]
        
        
class Comment_university_form(ModelForm):
    class Meta:
        model = Comment
        exclude = ["university"]
        
        
class Comment_institution_form(ModelForm):
    class Meta:
        model = Comment
        exclude = ["institution"]
        
        
def show_homepage(request):
    if request.user.is_authenticated():
        banners = Banner.objects.all()
        banner_top = None
        banner_bottom = None
        banner_right_short = None
        if banners:
            banner_top = Banner.objects.all().filter(banner_category='t')
            banner_bottom = Banner.objects.all().filter(banner_category='b')
            banner_right_short = Banner.objects.all().filter(banner_category='rs')
        
            if banner_top:
                banner_top = Banner.objects.all().filter(banner_category='t')[:1].get()
            if banner_bottom:
                banner_bottom = Banner.objects.all().filter(banner_category='b')[:1].get()
            if banner_right_short:
                banner_right_short = Banner.objects.all().filter(banner_category='rs')[:1].get()
        
        try:
            most_commented_articles = Article.objects.all().order_by('-comment_count')[:3]
            most_read_articles = Article.objects.all().order_by('-read_count')[:3]
            latest_files = File.objects.all().order_by('-upload_date')[:3]
            latest_articles = Article.objects.all().order_by('-pub_date')[:5]
            latest_articles_small = Article.objects.all().order_by('-pub_date')[:4]
        
            if Vocabulary.objects.all().count() > 0:
                daily_word = Vocabulary.objects.all().order_by('?')[:1].get()
            else:
                daily_word = None
        
            if Poll.objects.all().count() > 0:
                latest_poll = Poll.objects.all().order_by('-pub_date')[:1].get()
            else:
                latest_poll = None
                
            choices = Choice.objects.filter(poll=latest_poll)
            total_vote = 0
            for choice in choices:
                total_vote += choice.votes 
            print total_vote
        except Article.DoesNotExist:
            raise Http404
        
        dic = dict(most_commented_articles=most_commented_articles, most_read_articles=most_read_articles,
                   daily_word=daily_word, total_vote=total_vote, latest_poll=latest_poll,
                   latest_files=latest_files, latest_articles=latest_articles, 
                   latest_articles_small=latest_articles_small, banner_top=banner_top,
                   banner_bottom=banner_bottom, banner_right_short=banner_right_short)
        dic.update(csrf(request))
        
        return render_to_response('ehlel.html', dic,
                              context_instance=RequestContext(request))
    else:
        return render_to_response('homepage.html',
                                  context_instance=RequestContext(request))


@login_required
def show_medee(request):
    #Article model дотор байгаа article-уудыг pub_date-р нь ангилан авах
    articles = Article.objects.all().order_by('-pub_date')
    
    banners = Banner.objects.all()
    banner_right_long = None
    if banners:
        banner_right_long = Banner.objects.all().filter(banner_category='rl')
        
        if banner_right_long:
            banner_right_long = Banner.objects.all().filter(banner_category='rl')[:1].get()
    
    dic = dict(articles=articles, banner_right_long=banner_right_long)
    dic.update(csrf(request))
    
    return render_to_response('index.html', dic,
                              context_instance=RequestContext(request))
    
    
@login_required    
def show_files(request):
     #File model дотор байгаа file-уудыг file_name-р нь ангилан авах
    files = File.objects.all().order_by('-file_name')
    
    return render_to_response('index.html', {'files': files},
                              context_instance=RequestContext(request))
    
    
@login_required   
def show_profile(request, user_id):
    saved_articles = Saved_article.objects.all().filter(user_id=request.user.id)
    saved_universities = Saved_university.objects.all().filter(user_id=request.user.id)
    saved_institutions = Saved_institution.objects.all().filter(user_id=request.user.id)
    read_articles = Read_article.objects.all().filter(user_id=request.user.id)
    read_universities = Read_university.objects.all().filter(user_id=request.user.id)
    read_institutions = Read_institution.objects.all().filter(user_id=request.user.id)
    user = User.objects.get(pk=user_id)
    
    banners = Banner.objects.all()
    banner_bottom = None
    if banners:
        banner_bottom = Banner.objects.all().filter(banner_category='b')
        
        if banner_bottom:
            banner_bottom = Banner.objects.all().filter(banner_category='b')[:1].get()
    
    try:
        current_profile = RegistrationProfile.objects.filter(user=user)[:1].get()
    except RegistrationProfile.DoesNotExist:
        dic = dict(saved_articles=saved_articles, 
                   saved_universities=saved_universities, saved_institutions=saved_institutions,
                   read_articles=read_articles, read_universities=read_universities, 
                   read_institutions=read_institutions, banner_bottom=banner_bottom)
        dic.update(csrf(request))
        
        return render_to_response('article.html', dic,
                                  context_instance=RequestContext(request))
        
    dic = dict(current_profile=current_profile, saved_articles=saved_articles, 
                   saved_universities=saved_universities, saved_institutions=saved_institutions,
                   read_articles=read_articles, read_universities=read_universities, 
                   read_institutions=read_institutions, banner_bottom=banner_bottom)
    dic.update(csrf(request))
    
    return render_to_response('article.html', dic,
                              context_instance=RequestContext(request))
    
    
@login_required    
def show_about(request):
    try:
        about = About.objects.all()[:1].get()
        
        dic = dict(about=about)
        dic.update(csrf(request))
        
        return render_to_response('about.html', dic,
                      context_instance=RequestContext(request))

    except About.DoesNotExist:
        dic = dict(error=u"Одоохондоо мэдээлэл алга байна")
        dic.update(csrf(request))
        
        return render_to_response('about.html', dic,
                      context_instance=RequestContext(request))
        

@login_required    
def show_contact(request):
    try:
        contact = Contact.objects.all()[:1].get()
        
        dic = dict(contact=contact)
        dic.update(csrf(request))
        
        return render_to_response('contact.html', dic,
                                  context_instance=RequestContext(request))
        
    except Contact.DoesNotExist:
        dic = dict(error=u"Одоохондоо мэдээлэл байхгүй байна")
        dic.update(csrf(request))
        
        return render_to_response('contact.html', dic,
                                      context_instance=RequestContext(request))


@login_required    
def detail(request, article_id):
    read_articles = Read_article.objects.all().filter(user_id=request.user.id)
    read_universities = Read_university.objects.all().filter(user_id=request.user.id)
    read_institutions = Read_institution.objects.all().filter(user_id=request.user.id)
    user = User.objects.get(pk=request.user.id)
    article = Article.objects.get(pk=article_id)
    existing_article = Read_article.objects.all().filter(article_id=article)
    
    banners = Banner.objects.all()
    banner_right_long = None
    if banners:
        banner_right_long = Banner.objects.all().filter(banner_category='rl')
        
        if banner_right_long:
            banner_right_long = Banner.objects.all().filter(banner_category='rl')[:1].get()
    
    if (len(read_articles) + len(read_universities) + len(read_institutions)) > 5:
        read_article = Read_article.objects.all().filter(user_id=request.user.id)[:1].get()
        read_article.delete()
    if not existing_article:
        try:
            read_article = Read_article(article_id=article, user_id=user)
            read_article.save()
        except Article.DoesNotExist:
            raise Http404
    
    try:
        current_article = Article.objects.get(pk=article_id)
        comments = Comment.objects.filter(article=current_article)
        articles = Article.objects.all().order_by('-pub_date')[:5]
        categories = Category.objects.all().order_by('-category')
        
        current_article.read_count += 1
        current_article.save()
        
        dic = dict(current_article=current_article, comments=comments, articles=articles,
                    categories=categories, banner_right_long=banner_right_long, form=Comment_article_form(), user=user)
        dic.update(csrf(request))
    except Article.DoesNotExist:
        raise Http404
    
    return render_to_response('article.html', dic,
                              context_instance=RequestContext(request))
    

#@login_required
def add_article_comment(request, article_id):
    context = request.POST
    
    article = Article.objects.all().get(pk=article_id)
    article.comment_count += 1
    article.save()
    
    if context.has_key("body") and context["body"]:
        author = request.user.username
        
        #if context["author"]: author = context["author"]
        
        comment = Comment(article=Article.objects.get(pk=article_id))
        comment_form = Comment_article_form(context, instance=comment)
        comment_form.fields["author"].required = False
        
        comment = comment_form.save(commit=False)
        comment.author = author
        comment.save()
    return HttpResponseRedirect(reverse("toefl_app.views.detail", args=[article_id]))


@login_required
def add_file_comment(request, file_id):
    context = request.POST
    
    if context.has_key("body") and context["body"]:
        author = request.user.username
        
        #if context["author"]: author = context["author"]
        
        comment = Comment(file=File.objects.get(pk=file_id))
        comment_form = Comment_file_form(context, instance=comment)
        comment_form.fields["author"].required = False
        
        comment = comment_form.save(commit=False)
        comment.author = author
        comment.save()
    return HttpResponseRedirect(reverse("toefl_app.views.show_file", args=[file_id]))


@login_required
def add_university_comment(request, university_id):
    context = request.POST
    
    if context.has_key("body") and context["body"]:
        author = request.user.username
        
        #if context["author"]: author = context["author"]
        
        comment = Comment(university=University.objects.get(pk=university_id))
        comment_form = Comment_university_form(context, instance=comment)
        comment_form.fields["author"].required = False
        
        comment = comment_form.save(commit=False)
        comment.author = author
        comment.save()
    return HttpResponseRedirect(reverse("toefl_app.views.show_university", args=[university_id]))


@login_required
def add_institution_comment(request, institution_id):
    context = request.POST
    
    if context.has_key("body") and context["body"]:
        author = request.user.username
        
        #if context["author"]: author = context["author"]
        
        comment = Comment(institution=Institution.objects.get(pk=institution_id))
        comment_form = Comment_institution_form(context, instance=comment)
        comment_form.fields["author"].required = False
        
        comment = comment_form.save(commit=False)
        comment.author = author
        comment.save()
    return HttpResponseRedirect(reverse("toefl_app.views.show_institution", args=[institution_id]))


@login_required
@csrf_exempt
def vote(request, poll_id, choice_id):
    
    poll = get_object_or_404(Poll, pk=poll_id)
    selected_choice = poll.choice_set.get(pk=choice_id)
    selected_choice.votes += 1
    selected_choice.save()
    
    return HttpResponse("ok")
    
    
@login_required    
def show_category_article(request, category_id):
    try:
        current_category = Category.objects.get(pk=category_id)
        articles = Article.objects.filter(category=current_category)
        institutions = None
        universities = None
        dic = dict(articles=articles)
        
        if not articles:
             institutions = Institution.objects.filter(ins_category=current_category)
             dic = dict(institutions=institutions)
             if not institutions:
                 universities = University.objects.filter(uni_article_category=current_category)
                 dic = dict(universities=universities)
    except Category.DoesNotExist:
        raise Http404
    
    dic.update(csrf(request))
    
    return render_to_response('index.html', dic,
                              context_instance=RequestContext(request))
    

@login_required    
def show_file(request, file_id):
    try:
        current_file = File.objects.get(pk=file_id)
        articles = Article.objects.all().order_by('-pub_date')[:5]
        categories = Category.objects.all().order_by('-category')
        comments = Comment.objects.filter(file=current_file)
        
        dic = dict(current_file=current_file, articles=articles,
                    categories=categories, comments=comments, form=Comment_file_form(), user=request.user)
        dic.update(csrf(request))
    except Article.DoesNotExist:
        raise Http404
    
    return render_to_response('article.html', dic,
                              context_instance=RequestContext(request))
    

@login_required    
def show_universities(request, university_id):
    dic = {}
    
    if university_id == '1':
        universities = University.objects.filter(uni_category=1).order_by('uni_name')
        category = u'Ану, Канадын Их, Дээд сургууль'
        
        dic = dict(universities=universities, category=category, user=request.user)
        dic.update(csrf(request))
    elif university_id == '2':
        universities = University.objects.filter(uni_category=2).order_by('uni_name')
        category = u'Их Британи, Австралийн Их, Дээд сургууль'
        
        dic = dict(universities=universities, category=category, user=request.user)
        dic.update(csrf(request))
    elif university_id == '3':
        universities = University.objects.filter(uni_category=3).order_by('uni_name')
        category = u'Европийн Их, Дээд сургууль'
        
        dic = dict(universities=universities, category=category, user=request.user)
        dic.update(csrf(request))
    elif university_id == '4':
        universities = University.objects.filter(uni_category=4).order_by('uni_name')
        category = u'Азийн Их, Дээд сургууль'
        
    banners = Banner.objects.all()
    banner_top = None
    banner_bottom = None
    if banners:
        banner_top = Banner.objects.all().filter(banner_category='t')
        banner_bottom = Banner.objects.all().filter(banner_category='b')
        
        if banner_top:
            banner_top = Banner.objects.all().filter(banner_category='t')[:1].get()
        if banner_bottom:
            banner_bottom = Banner.objects.all().filter(banner_category='b')[:1].get()
    
    dic = dict(universities=universities, banner_top=banner_top, banner_bottom=banner_bottom,
               category=category)
    dic.update(csrf(request))
    
    return render_to_response('index.html', dic, 
                              context_instance=RequestContext(request))
    

@login_required
def show_university(request, university_id):
    read_articles = Read_article.objects.all().filter(user_id=request.user.id)
    read_universities = Read_university.objects.all().filter(user_id=request.user.id)
    read_institutions = Read_institution.objects.all().filter(user_id=request.user.id)
    user = User.objects.get(pk=request.user.id)
    university = University.objects.get(pk=university_id)
    existing_university = Read_university.objects.all().filter(university_id=university)
    
    if (len(read_articles) + len(read_universities) + len(read_institutions)) > 5:
        read_university = Read_university.objects.all().filter(user_id=request.user.id)[:1].get()
        read_university.delete()
    if not existing_university:
        try:
            read_university = Read_university(university_id=university, user_id=user)
            read_university.save()
        except University.DoesNotExist:
            raise Http404
        
    banners = Banner.objects.all()
    banner_right_long = None
    if banners:
        banner_right_long = Banner.objects.all().filter(banner_category='rl')
        
        if banner_right_long:
            banner_right_long = Banner.objects.all().filter(banner_category='rl')[:1].get()
    
    try:
        current_university = University.objects.get(pk=university_id)
        articles = Article.objects.all().filter(category=current_university.uni_article_category)[:4]
        categories = Category.objects.all().order_by('-category')
        comments = Comment.objects.filter(university=current_university)
        
        dic = dict(current_university=current_university, articles=articles,
                    categories=categories, banner_right_long=banner_right_long,
                    comments=comments, form=Comment_university_form(), user=user)
        dic.update(csrf(request))
    except University.DoesNotExist:
        raise Http404
    
    return render_to_response('article.html', dic,
                              context_instance=RequestContext(request))
    

@login_required
def show_institutions(request):
    institutions = Institution.objects.all().order_by('ins_name')
    
    banners = Banner.objects.all()
    banner_top = None
    banner_bottom = None
    if banners:
        banner_top = Banner.objects.all().filter(banner_category='t')
        banner_bottom = Banner.objects.all().filter(banner_category='b')
        
        if banner_top:
            banner_top = Banner.objects.all().filter(banner_category='t')[:1].get()
        if banner_bottom:
            banner_bottom = Banner.objects.all().filter(banner_category='b')[:1].get()
    
    dic = dict(institutions=institutions, banner_top=banner_top, banner_bottom=banner_bottom)
    dic.update(csrf(request))
    
    return render_to_response('index.html', dic, 
                              context_instance=RequestContext(request))
    
    
@login_required    
def show_institution(request, institution_id):
    read_articles = Read_article.objects.all().filter(user_id=request.user.id)
    read_universities = Read_university.objects.all().filter(user_id=request.user.id)
    read_institutions = Read_institution.objects.all().filter(user_id=request.user.id)
    user = User.objects.get(pk=request.user.id)
    institution = Institution.objects.get(pk=institution_id)
    existing_institution = Read_institution.objects.all().filter(institution_id=institution)
    
    if (len(read_articles) + len(read_universities) + len(read_institutions)) > 5:
        read_institution = Read_institution.objects.all().filter(user_id=request.user.id)[:1].get()
        read_institution.delete()
    if not existing_institution:
        try:
            read_institution = Read_institution(institution_id=institution, user_id=user)
            read_institution.save()
        except Institution.DoesNotExist:
            raise Http404
        
    banners = Banner.objects.all()
    banner_top = None
    if banners:
        banner_top = Banner.objects.all().filter(banner_category='t')
        
        if banner_top:
            banner_top = Banner.objects.all().filter(banner_category='t')[:1].get()
    
    try:
        current_institution = Institution.objects.get(pk=institution_id)
        articles = Article.objects.all().filter(category=current_institution.ins_category)[:5]
        comments = Comment.objects.filter(institution=current_institution)
        
        dic = dict(current_institution=current_institution, articles=articles, banner_top=banner_top,
                   comments=comments, form=Comment_institution_form(), user=user)
        dic.update(csrf(request))
    except Institution.DoesNotExist:
        raise Http404
    
    return render_to_response('article.html', dic,
                              context_instance=RequestContext(request))
    

@login_required
def search(request):
    query_string = ''
    found_entries = None
    if ('q' in request.GET) and request.GET['q'].strip():
        query_string = request.GET['q']
        
        #Article
        article_query = get_query(query_string, ['header', 'content'])
        found_articles = Article.objects.filter(article_query).order_by('-pub_date')
        #File
        file_query = get_query(query_string, ['file_name', 'file_description'])
        found_files = File.objects.filter(file_query).order_by('-upload_date')
        #University
        university_query = get_query(query_string, ['uni_name', 'uni_category', 'uni_address', 
                                                    'uni_schedule', 'uni_scholarship'])
        found_universities = University.objects.filter(university_query).order_by('-uni_name')
        #Institution
        institution_query = get_query(query_string, ['ins_name', 'ins_address', 
                                                    'ins_intro', 'ins_schedule'])
        found_institutions = Institution.objects.filter(institution_query).order_by('-ins_name')
        
        dic = dict(found_articles=found_articles, found_files=found_files, query_string=query_string,
                   found_universities=found_universities, found_institutions=found_institutions)
        dic.update(csrf(request))

    return render_to_response('search.html', dic, context_instance=RequestContext(request))


@login_required
def save_article(request, article_id):
    saved_articles = Saved_article.objects.all().filter(user_id=request.user.id)
    saved_universities = Saved_university.objects.all().filter(user_id=request.user.id)
    saved_institutions = Saved_institution.objects.all().filter(user_id=request.user.id)
    user = User.objects.get(pk=request.user.id)
    article = Article.objects.get(pk=article_id)
    existing_article = Saved_article.objects.all().filter(article_id=article)
    
    try:
        current_profile = RegistrationProfile.objects.filter(user=user)[:1].get()
    except RegistrationProfile.DoesNotExist:
        dic = dict(saved_articles=saved_articles, 
                   saved_universities=saved_universities, saved_institutions=saved_institutions)
        dic.update(csrf(request))
        return render_to_response('article.html', dic,
                              context_instance=RequestContext(request))
    
    if (len(saved_articles) + len(saved_universities) + len(saved_institutions)) < 10:
        if not existing_article:
            try:
                save_article = Saved_article(article_id=article, user_id=user)
                save_article.save()
                saved_articles = Saved_article.objects.all().filter(user_id=request.user.id)
            except Article.DoesNotExist:
                raise Http404
            
            dic = dict(current_profile=current_profile, saved_articles=saved_articles, 
                       saved_universities=saved_universities, saved_institutions=saved_institutions)
        else:
            dic = dict(current_profile=current_profile, saved_articles=saved_articles, 
                   saved_universities=saved_universities, saved_institutions=saved_institutions,
                   error=u'Та энэ мэдээг хадгалчихсан байна!')
        
    else:
        dic = dict(current_profile=current_profile, saved_articles=saved_articles, 
                   saved_universities=saved_universities, saved_institutions=saved_institutions,
                   error=u'Та дээд тал нь 10 мэдээ хадгалах боломжтой!')
    
    dic.update(csrf(request))
    return render_to_response('article.html', dic,
                              context_instance=RequestContext(request))
    

@login_required    
def save_university(request, university_id):
    saved_articles = Saved_article.objects.all().filter(user_id=request.user.id)
    saved_universities = Saved_university.objects.all().filter(user_id=request.user.id)
    saved_institutions = Saved_institution.objects.all().filter(user_id=request.user.id)
    user = User.objects.get(pk=request.user.id)
    university = University.objects.get(pk=university_id)
    existing_university = Saved_university.objects.all().filter(university_id=university)
    
    try:
        current_profile = RegistrationProfile.objects.filter(user=user)[:1].get()
    except RegistrationProfile.DoesNotExist:
        dic = dict(saved_articles=saved_articles, 
                   saved_universities=saved_universities, saved_institutions=saved_institutions)
        dic.update(csrf(request))
        return render_to_response('article.html', dic,
                              context_instance=RequestContext(request))
    
    if (len(saved_articles) + len(saved_universities) + len(saved_institutions)) < 10:
        if not existing_university:
            try:
                save_university = Saved_university(university_id=university, user_id=user)
                save_university.save()
                saved_universities = Saved_university.objects.all().filter(user_id=request.user.id)
            except University.DoesNotExist:
                raise Http404
            
            dic = dict(current_profile=current_profile, saved_articles=saved_articles, 
                       saved_universities=saved_universities, saved_institutions=saved_institutions)
        else:
            dic = dict(current_profile=current_profile, saved_articles=saved_articles, 
                   saved_universities=saved_universities, saved_institutions=saved_institutions,
                   error=u'Та энэ мэдээг хадгалчихсан байна!')
        
    else:
        dic = dict(current_profile=current_profile, saved_articles=saved_articles, 
                   saved_universities=saved_universities, saved_institutions=saved_institutions,
                   error=u'Та дээд тал нь 10 мэдээ хадгалах боломжтой!')
    
    dic.update(csrf(request))
    return render_to_response('article.html', dic,
                              context_instance=RequestContext(request))
    

@login_required
def save_institution(request, institution_id):
    saved_articles = Saved_article.objects.all().filter(user_id=request.user.id)
    saved_universities = Saved_university.objects.all().filter(user_id=request.user.id)
    saved_institutions = Saved_institution.objects.all().filter(user_id=request.user.id)
    user = User.objects.get(pk=request.user.id)
    institution = Institution.objects.get(pk=institution_id)
    existing_institution = Saved_institution.objects.all().filter(institution_id=institution)
    
    try:
        current_profile = RegistrationProfile.objects.filter(user=user)[:1].get()
    except RegistrationProfile.DoesNotExist:
        dic = dict(saved_articles=saved_articles, 
                   saved_universities=saved_universities, saved_institutions=saved_institutions)
        dic.update(csrf(request))
        return render_to_response('article.html', dic,
                              context_instance=RequestContext(request))
    
    if (len(saved_articles) + len(saved_universities) + len(saved_institutions)) < 10:
        if not existing_institution:
            try:
                save_institution = Saved_institution(institution_id=institution, user_id=user)
                save_institution.save()
                saved_institutions = Saved_institution.objects.all().filter(user_id=request.user.id)
            except Institution.DoesNotExist:
                raise Http404
            
            dic = dict(current_profile=current_profile, saved_articles=saved_articles, 
                       saved_universities=saved_universities, saved_institutions=saved_institutions)
        else:
            dic = dict(current_profile=current_profile, saved_articles=saved_articles, 
                   saved_universities=saved_universities, saved_institutions=saved_institutions,
                   error=u'Та энэ мэдээг хадгалчихсан байна!')
        
    else:
        dic = dict(current_profile=current_profile, saved_articles=saved_articles, 
                   saved_universities=saved_universities, saved_institutions=saved_institutions,
                   error=u'Та дээд тал нь 10 мэдээ хадгалах боломжтой!')
    
    dic.update(csrf(request))
    return render_to_response('article.html', dic,
                              context_instance=RequestContext(request))
        
        
@login_required        
def delete_article(request, article_id):
    user = User.objects.get(pk=request.user.id)
    try:
        article = Article.objects.get(pk=article_id)
        delete_article = Saved_article.objects.all().filter(article_id=article)
        delete_article.delete()
    except Article.DoesNotExist:
            raise Http404
        
    saved_articles = Saved_article.objects.all().filter(user_id=request.user.id)
    saved_universities = Saved_university.objects.all().filter(user_id=request.user.id)
    saved_institutions = Saved_institution.objects.all().filter(user_id=request.user.id)
    current_profile = RegistrationProfile.objects.filter(user=user)[:1].get()
    
    dic = dict(current_profile=current_profile, saved_articles=saved_articles, 
               saved_universities=saved_universities, saved_institutions=saved_institutions)
    dic.update(csrf(request))
    
    return render_to_response('article.html', dic,
                              context_instance=RequestContext(request))
        

@login_required    
def delete_university(request, university_id):
    user = User.objects.get(pk=request.user.id)
    try:
        university = University.objects.get(pk=university_id)
        delete_university = Saved_university.objects.all().filter(university_id=university)
        delete_university.delete()
    except University.DoesNotExist:
            raise Http404
        
    saved_articles = Saved_article.objects.all().filter(user_id=request.user.id)
    saved_universities = Saved_university.objects.all().filter(user_id=request.user.id)
    saved_institutions = Saved_institution.objects.all().filter(user_id=request.user.id)
    current_profile = RegistrationProfile.objects.filter(user=user)[:1].get()
    
    dic = dict(current_profile=current_profile, saved_articles=saved_articles, 
               saved_universities=saved_universities, saved_institutions=saved_institutions)
    dic.update(csrf(request))
    
    return render_to_response('article.html', dic,
                              context_instance=RequestContext(request))
        

@login_required
def delete_institution(request, institution_id):
    user = User.objects.get(pk=request.user.id)
    try:
        institution = Institution.objects.get(pk=institution_id)
        delete_institution = Saved_institution.objects.all().filter(institution_id=institution)
        delete_institution.delete()
    except Institution.DoesNotExist:
            raise Http404
        
    saved_articles = Saved_article.objects.all().filter(user_id=request.user.id)
    saved_universities = Saved_university.objects.all().filter(user_id=request.user.id)
    saved_institutions = Saved_institution.objects.all().filter(user_id=request.user.id)
    current_profile = RegistrationProfile.objects.filter(user=user)[:1].get()
    
    dic = dict(current_profile=current_profile, saved_articles=saved_articles, 
               saved_universities=saved_universities, saved_institutions=saved_institutions)
    dic.update(csrf(request))
    
    return render_to_response('article.html', dic,
                              context_instance=RequestContext(request))
    

@login_required    
def edit_profile(request):
    user = User.objects.get(pk=request.user.id)
    user_profile = RegistrationProfile.objects.get(user=user)
    
    dic = dict(firstname=user_profile.firstname, lastname=user_profile.lastname, phone=user_profile.phone,
               motto=user_profile.motto, image=user_profile.image)
    dic.update(csrf(request))
    
    return render_to_response('edit_profile.html', dic,
                              context_instance=RequestContext(request))
    

@login_required    
def edit(request):
    saved_articles = Saved_article.objects.all().filter(user_id=request.user.id)
    saved_universities = Saved_university.objects.all().filter(user_id=request.user.id)
    saved_institutions = Saved_institution.objects.all().filter(user_id=request.user.id)
    user = User.objects.get(pk=request.user.id)
    user_profile = RegistrationProfile.objects.get(user=user)
        
    if request.method == 'POST':
        if request.POST.get('firstname'):
            user_profile.firstname = request.POST.get('firstname')
        if request.POST.get('lastname'):
            user_profile.lastname =  request.POST.get('lastname')
        if request.POST.get('phone'):
            user_profile.phone = request.POST.get('phone')
        if request.POST.get('motto'):
            user_profile.motto = request.POST.get('motto')
        if request.FILES['image']:
            user_profile.image.save(request.FILES['image'].name, request.FILES['image'])
        user_profile.save()
        
    
    user = User.objects.get(pk=request.user.id)
    current_profile = RegistrationProfile.objects.get(user=user)
    
    dic = dict(current_profile=current_profile, saved_articles=saved_articles, 
                   saved_universities=saved_universities, saved_institutions=saved_institutions)
    dic.update(csrf(request))
    
    return render_to_response('article.html', dic,
                              context_instance=RequestContext(request))

        
@login_required    
def download(request, file_id):
    try:
        file = get_object_or_404(File, pk=file_id)
    except File.DoesNotExist:
        raise Http404
    
    return serve_file(request, file.file, save_as=True)


@login_required
def about_toefl(request):
     try:
        about_toefl = About_toefl.objects.all()[:1].get()
        
        dic = dict(about_toefl=about_toefl)
        dic.update(csrf(request))
        
        return render_to_response('about_toefl.html', dic,
                                  context_instance=RequestContext(request))
        
     except About_toefl.DoesNotExist:
        dic = dict(error=u"Одоохондоо мэдээлэл байхгүй байна")
        dic.update(csrf(request))
        
        return render_to_response('about_toefl.html', dic,
                                      context_instance=RequestContext(request))
    
def normalize_query(query_string,
                    findterms=re.compile(r'"([^"]+)"|(\S+)').findall,
                    normspace=re.compile(r'\s{2,}').sub):
    ''' Splits the query string in invidual keywords, getting rid of unecessary spaces
        and grouping quoted words together.
        Example:
        
        >>> normalize_query('  some random  words "with   quotes  " and   spaces')
        ['some', 'random', 'words', 'with quotes', 'and', 'spaces']
    
    '''
    return [normspace(' ', (t[0] or t[1]).strip()) for t in findterms(query_string)] 

def get_query(query_string, search_fields):
    ''' Returns a query, that is a combination of Q objects. That combination
        aims to search keywords within a model by testing the given search fields.
    
    '''
    query = None # Query to search for every search term        
    terms = normalize_query(query_string)
    for term in terms:
        or_query = None # Query to search for a given term in each field
        for field_name in search_fields:
            q = Q(**{"%s__icontains" % field_name: term})
            if or_query is None:
                or_query = q
            else:
                or_query = or_query | q
        if query is None:
            query = or_query
        else:
            query = query & or_query
    return query